<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController {

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        $nickname       =   I('nickname');
        $map['status']  =   array('egt',0);
        if(!empty($nickname)){
            if(is_numeric($nickname)){
                $map['uid|username']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
            }else{
                $map['username']    =   array('like', '%'.(string)$nickname.'%');
            }
        }

        $list   = $this->lists(M('UcenterMember'), $map,'id asc');
        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');
        $data   =   $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid'=>$uid))->save($data);

        if($res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        $this->meta_title = '修改密码';
        $this->display();
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }



    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Ucenter_Member', $map);
                break;
            case 'resumeuser':
                $this->resume('Ucenter_Member', $map );
                break;
            case 'deleteuser':
                $this->delete('Ucenter_Member', $map );
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $password = '', $repassword = '', $email = '', $group_id=''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $email);
            if(0 < $uid){ //注册成功
                $user_group = array('uid' => $uid, 'group_id' => $group_id);
                if(!M('auth_group_access')->add($user_group)){
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！',U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $group=M('auth_group')->where(array('module'=>'admin'))->field('id,title')->select();
            $this->assign('group',$group);
            $this->meta_title = '新增用户';
            $this->display();
        }
    }

    /**
     * 代理管理
     */
    public function agent(){
        $username       =   I('username');
        $status=I('status');
        $map['status']  = ($status=='')? array('egt',0):$status;
        $map['type']=1;
        if(!empty($username)){
            if(is_numeric($username)){
                $map['uid|username']=   array(intval($username),array('like','%'.$username.'%'),'_multi'=>true);
            }else{
                $map['username']    =   array('like', '%'.(string)$username.'%');
            }
        }
        $list   = $this->lists(M('agent'), $map,'uid asc');
        $this->assign('_list', $list);
        $this->meta_title = '代理用户信息';
        $this->display();
    }


    /**
     * 代理状态修改
     * @author qixing <zhuyajie@topthink.net>
     */
    public function changeAngentStatus($method=null){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('agent', $map,2);
                break;
            case 'resumeuser':
                $this->resume('agent', $map ,array( 'success'=>'审核成功！', 'error'=>'审核失败！'));
                break;
            case 'deleteuser':
                $this->delete('agent', $map );
                break;
            case 'deletereportaccount':
                $this->delete('report_member', $map);
                break;    
            default:
                $this->error('参数非法');
        }
    }

    //编辑代理
    public function editAgent(){
        $id=I('get.uid');
        $data=M('agent')->where(array('uid'=>$id))->find();
        $this->assign('data',$data);
        $this->meta_title = '编辑代理用户';
        $this->display();
    }

    //保存登记账户信息
    public function saveAgent(){
        $data=I('post.');
        if(empty($data)){
            $this->error ("请填写完整数据");
        }
    
         /* 检测密码 */
        if( $data['password'] != $data['repassword']){
           $this->error('密码和重复密码不一致！');
         }
        unset($data['repassword']);
        $data['password']=think_ucenter_md5($data['password'],UC_AUTH_KEY);

        if(empty($data['uid'])){ //新增数据
            $data['reg_time']=time();
            $uid    = M('Agent')->add($data);
            if(!$uid){
                $this->error ("新增出错");
            }else{
                $this->success ('新增成功！', U('agent'));
            }
        } else { //更新数据
            $data['update_time']=time();
            $status = M('Agent')->save($data);
            if(false === $status){
                $this->error ("更新出错");
            }else{
                $this->success ('更新成功！', U('agent') );
            }
        }
    }


   


     /**
     * 登记账户管理
     */
    public function specificAccount(){
        $username       =   I('username');
        $map['type']  =2;
        if(!empty($username)){
            if(is_numeric($username)){
                $map['uid|username']=   array(intval($username),array('like','%'.$username.'%'),'_multi'=>true);
            }else{
                $map['username']    =   array('like', '%'.(string)$username.'%');
            }
        }
        $map['status']=array('gt',0);
        $list   = $this->lists(M('agent'), $map,'uid asc');
        $this->assign('_list', $list);
        $this->meta_title = '代理用户信息';
        $this->display();
    }

    /**
     * 登记账户添加
     */
    public function addSpecificAccount(){
         $this->meta_title = '新增登记用户';
         $this->display();
    }

    public function editSpecificAccount(){
        $id=I('get.uid');
        $data=M('agent')->where(array('uid'=>$id))->find();

        $this->assign('data',$data);
        $this->meta_title = '编辑账户';
        $this->display('addSpecificAccount');
    }


    //保存登记账户信息
    public function saveSpecificAccount(){
        $data=I('post.');
        if(empty($data)){
            $this->error ("请填写完整数据");
        }
    
         /* 检测密码 */
        if( $data['password'] != $data['repassword']){
           $this->error('密码和重复密码不一致！');
         }
        unset($data['repassword']);
        $data['type']=2;
        $data['status']=1;
        $data['password']=think_ucenter_md5($data['password'],UC_AUTH_KEY);

    
        if(empty($data['uid'])){ //新增数据
            $data['reg_time']=time();
            $uid    = M('Agent')->add($data);
            if(!$uid){
                $this->error ("新增出错");
            }else{
                $this->success ('新增成功！', U('specificAccount'));
            }
        } else { //更新数据
            $data['update_time']=time();
            $status = M('Agent')->save($data);
            if(false === $status){
                $this->error ("更新出错");
            }else{
                $this->success ('更新成功！', U('specificAccount') );
            }
        }
    }



    //入学报到账户管理

    public function reportAccount(){
        $username       =   I('username');
        if(!empty($username)){
            if(is_numeric($username)){
                $map['uid|username']=   array(intval($username),array('like','%'.$username.'%'),'_multi'=>true);
            }else{
                $map['username']    =   array('like', '%'.(string)$username.'%');
            }
        }
        $map['status']=array('gt',0);
        $list   = $this->lists(M('report_member'), $map,'id asc');
        $this->assign('_list', $list);
        $this->meta_title = '入学报到账户信息';
        $this->display();
    }


    /**
     * 入学报到账户添加
     */
    public function addReportAccount(){
         $this->meta_title = '新增入学报到账户';
          $this->display();
    }

     public function editReportAccount(){
        $id=I('get.id');
        $data=M('report_member')->where(array('id'=>$id))->find();
        $this->assign('data',$data);
        $this->meta_title = '编辑账户';
        $this->display('addReportAccount');
    }


    //保存入学报到账户信息
    public function saveReportAccount(){
        $data=I('post.');
        if(empty($data)){
            $this->error ("请填写完整数据");
        }
    
         /* 检测密码 */
        if( $data['password'] != $data['repassword']){
           $this->error('密码和重复密码不一致！');
         }
        unset($data['repassword']);
        $data['password']=think_ucenter_md5($data['password'],UC_AUTH_KEY);
    

        if(empty($data['id'])){ //新增数据
            $data['create_time']=time();
            $uid    = M('report_member')->add($data);
            if(!$uid){
                $this->error ("新增出错");
            }else{
                $this->success ('新增成功！', U('reportAccount') );
            }
        } else { //更新数据
            $data['update_time']=time();
            $status = M('report_member')->save($data);
            if(false === $status){
                $this->error ("更新出错");
            }else{
                $this->success ('更新成功！', U('reportAccount') );
            }
        }
    }



    /**
     * 部门管理
     */
    public function department(){

        $list   = $this->lists(M('department_info'), array(),'id asc');
        $this->assign('_list', $list);
        $this->meta_title = '部门管理信息';
        $this->display();
    }

    public function addDepartment(){
        $this->meta_title = '新增部门';
        $this->display('editdepartment');
    }

    public function editDepartment(){
        $id=I('get.id');
        $data=M('department_info')->where(array('id'=>$id))->field('id,title')->find();
        $this->assign('data',$data);
        $this->meta_title = '编辑部门';
        $this->display('editdepartment');
    }

    public function saveDepartment(){
        $data=I('post.');
        if(empty($data)){
            $this->error ("请填写完整数据");
        }

        if(empty($data['id'])){ //新增数据
            $data['create_time']=time();
            $res = M('department_info')->add($data);
            if(!$res){
                $this->error ("新增出错");
            }else{
                $this->success ('新增成功！', U('department') );
            }
        } else { //更新数据
            $data['update_time']=time();
            $status = M('department_info')->save($data);
            if(false === $status){
                $this->error ("更新出错");
            }else{
                $this->success ('更新成功！', U('department') );
            }
        }
    }



    public function deleteDepartment(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        $re = M('department_info')->where($map)->delete();
        if($re!==false){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }




    //班级管理
    public function classManage(){
        $list   = $this->lists(M('class'), array(),'id asc');
        $this->assign('_list', $list);
        $this->meta_title = '班级管理信息';
        $this->display();
    }

    //添加班级
    public function addClass($title = '', $password = '', $repassword = ''){
            $this->meta_title = '新增班级';
            $this->display('addclass');
    }

     //修改班级
     public function editClass(){
        $id=I('get.id');
        $data=M('class')->where(array('id'=>$id))->find();
        $this->assign('data',$data);
        $this->meta_title = '编辑班级';
        $this->display('addclass');
    }


    //保存入学报到账户信息
    public function saveClass(){
      if(IS_POST){
          $data=I('post.');
        if(empty($data)){
            $this->error ("请填写完整数据");
        }
         /* 检测密码 */
        if( $data['password'] != $data['repassword']){
           $this->error('密码和重复密码不一致！');
         }
        unset($data['repassword']);
        $data['password']=think_ucenter_md5($data['password'],UC_AUTH_KEY);


        if(empty($data['id'])){ //新增数据
            $data['create_time']=time();
            $uid    = M('class')->add($data);
            if(!$uid){
                $this->error ("新增出错");
            }else{
                $this->success ('新增成功！', U('classManage') );
            }
        } else { //更新数据
            $data['update_time']=time();
            $status = M('class')->save($data);
            if(false === $status){
                $this->error ("更新出错");
            }else{
                $this->success ('更新成功！', U('classManage') );
            }
        }


      }
   }



    public function deleteClass(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        $re = M('class')->where($map)->delete();
        if($re!==false){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }


    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

}
